package org.odefu.model.project;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class Table implements Named
{
	private final List<Row> rows = new ArrayList<Row>();

	private final String name;

	Table(final String name)
	{
		this.name = name;
	}

	@Override
	public String name()
	{
		return name;
	}

	public String fileName()
	{
		return name.toLowerCase() + ".json";
	}

	public Row createRow(final String name)
	{
		final Row row = new Row(name);
		add(row);
		return row;
	}

	/**
	 * Returns an unmodifiable view to the rows.
	 * 
	 * @return
	 */
	public List<Row> rows()
	{
		return Collections.unmodifiableList(rows);
	}

	/**
	 * Get the row at index.
	 * 
	 * @param index
	 * @return
	 */
	public Row row(final int index)
	{
		return rows.get(index);
	}

	/**
	 * Adds a new row to this table.
	 * 
	 * @param row
	 */
	public void add(final Row row)
	{
		if (!rows.contains(row))
		{
			rows.add(row);
		}
	}

	public void add(final Row row, final int index)
	{
		if (!rows.contains(row))
		{
			rows.add(index, row);
		}
	}

	public Row remove(final int index)
	{
		return rows.remove(index);
	}

	public boolean remove(final Row row)
	{
		return rows.remove(row);
	}

	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + (name == null ? 0 : name.hashCode());
		result = prime * result + (rows == null ? 0 : rows.hashCode());
		return result;
	}

	@Override
	public boolean equals(final Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (!(obj instanceof Table))
		{
			return false;
		}
		final Table other = (Table) obj;
		if (name == null)
		{
			if (other.name != null)
			{
				return false;
			}
		}
		else if (!name.equals(other.name))
		{
			return false;
		}
		if (rows == null)
		{
			if (other.rows != null)
			{
				return false;
			}
		}
		else if (!rows.equals(other.rows))
		{
			return false;
		}
		return true;
	}
}
